//
//  LXJTabBar.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/3/26.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

/// tabBar 的代理协议
protocol LXJTabBarDelegate : NSObjectProtocol {
    func publishWeiBoAction()
}

class LXJTabBar: UITabBar {
    // MARK: 控件的懒加载
    lazy var composeButton: UIButton = {
        let button = UIButton()
        /// 设置摁扭的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        /// 设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        /// 大小适配
        button.sizeToFit()
        
        /// 监听摁扭的点击事件
        button.addTarget(self, action: #selector(composeButtonDidSelectedAction), for: .touchUpInside)
        
        return button
    }()
    
    // MARK: 重写自定义构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        // fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupUI()
    }
    
    // MARK: 界面搭建
    func setupUI() -> Void {
        /// 添加子控件
        addSubview(composeButton)
    }
    
    // MARK: 设置发微博摁扭居中
    override func layoutSubviews() {
        super.layoutSubviews()
        /// 设置摁扭的中心点
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        /// 设置每个摁扭的宽度
        let buttonWidth = width / 5.0
        
        /// 设置摁扭的宽及 x 坐标
        var index = 0
        
        for subview in subviews {
            //            print(subviews[i])/// UITabBarButton
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                /// 设置宽度
                subview.width = buttonWidth
                /// 设置 x 坐标[这句话有问题]
                subview.x = CGFloat(index) * buttonWidth
                
                index += 1
                
                /// 设置发现摁扭后移一个宽度
                if index == 2 {
                    index = 3
                }
            }
        }
    }
    // MARK: 设置代理对象和闭包属性
    weak var lxj_delegate: LXJTabBarDelegate?
    var publishWeiBoActionClosure: (() -> ())?
    
    
    // MARK: 监听发微博摁扭的点击事件
    @objc private func composeButtonDidSelectedAction() -> Void {
        /// 执行代理方法
        lxj_delegate?.publishWeiBoAction()
        /// 执行闭包
        publishWeiBoActionClosure?()
    }
}
